C++ High Performance by Björn Andrist Viktor Sehr

C++ High Performance by Björn Andrist Viktor Sehr

Author:Björn Andrist, Viktor Sehr
Language: eng
Format: epub
Publisher: Packt
Published: 2020-12-10T11:44:53+00:00


The following code will oblige the compiler to instantiate two distinct functions: one squares the value and one cubes the value:

auto x2 = const_pow_n<2>(4.0f); // Square auto x3 = const_pow_n<3>(4.0f); // Cube

Note the difference between the template parameter N and the function parameter v. For every value of N, the compiler generates a new function. However, v is passed as a regular parameter and, as such, does not result in a new function.

Providing specializations of a template

By default, the compiler will generate regular C++ code whenever we use a template with new parameters. But it's also possible to provide a custom implementation for certain values of the template parameters. Say, for example, that we want to provide the regular C++ code of our const_pow_n() function when it's used with integers and the value of N is 2. We could write a template specialization for this case, as follows:

template<> auto const_pow_n<2, int>(const int& v) { return v * v; }



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.